<template>
  <view class="form-container">
    <view class="form-card">
      <view class="form-header">
        <text class="form-title">订单信息</text>
        <view class="decor-line"></view>
      </view>

      <!-- 订单编号 -->
      <view class="form-item">
        <view class="item-label">
          <view class="cuIcon-list"></view>
          订单编号
        </view>
        <view class="item-value">{{ ruleForm.dingdanbianhao }}</view>
      </view>

      <!-- 商品信息 -->
      <view class="form-item">
        <view class="item-label">
          <view class="cuIcon-goods"></view>
          商品名称
        </view>
        <input
          class="item-input"
          v-model="ruleForm.shangpinmingcheng"
          placeholder="请输入商品名称"
          disabled
        />
      </view>

      <!-- 图片上传 -->
      <!-- @tap="tupianTap" -->
      <view class="form-item">
        <view class="item-label">
          <view class="cuIcon-pic"></view>
          商品图片
        </view>
        <image
          class="upload-image"
          :src="_imgUrl + ruleForm.tupian || '/static/upload.png'"
          mode="aspectFill"
        ></image>
      </view>

      <!-- 价格数量 -->
      <view class="price-group">
        <view class="form-item half">
          <view class="item-label">单价</view>
          <input
            class="item-input"
            type="number"
            disabled
            v-model="ruleForm.jiage"
          />
        </view>
        <view class="form-item half">
          <view class="item-label">数量</view>
          <input
            class="item-input"
            v-model.number="ruleForm.spNumber"
            @input="onInput"
          />
        </view>
      </view>
      <!-- type="number" -->
      <!-- 总金额 -->
      <view class="form-item total-price">
        <view class="item-label">总金额</view>
        <view class="price-value">¥{{ zongjine }}</view>
      </view>

      <!-- 购买日期 -->
      <!-- <view class="form-item">
        <view class="item-label">
          <view class="cuIcon-calendar"></view>
          购买日期
        </view>
        <picker class="date-picker" mode="date" @change="goumairiqiChange">
          <view>{{ ruleForm.goumairiqi || "选择购买日期" }}</view>
        </picker>
      </view> -->

      <!-- 收货地址 -->
      <view class="form-item">
        <view class="item-label">
          <view class="cuIcon-location"></view>
          收货地址
        </view>
        <picker
          class="address-picker"
          @change="addressChange"
          :range="addressList"
        >
          <view>{{ ruleForm.shouhuodizhi || "选择收货地址" }}</view>
        </picker>
      </view>

      <!-- 提交按钮 -->
      <view class="submit-btn" @tap="onSubmitTap">
        <text>提交订单</text>
        <view class="cuIcon-check"></view>
      </view>
    </view>
  </view>
</template>
<script>
import wPicker from "@/components/w-picker/w-picker.vue";

export default {
  data() {
    return {
      ruleForm: {
        dingdanbianhao: this.getUUID(),
        shangpinmingcheng: "",
        tupian: "",
        jiage: "",
        shuliang: "",
        zongjine: "",
        goumairiqi: "",
        nonghuzhanghao: "",
        nonghuxingming: "",
        yonghuming: "",
        yonghuxingming: "",
        shoujihaoma: "",
        shouhuodizhi: "",
        ispay: "",
        userid: "",
        spNumber: 1,
      },
      // 登陆用户信息
      user: {},
      ro: {
        dingdanbianhao: false,
        shangpinmingcheng: false,
        tupian: false,
        jiage: false,
        shuliang: false,
        zongjine: false,
        goumairiqi: false,
        nonghuzhanghao: false,
        nonghuxingming: false,
        yonghuming: false,
        yonghuxingming: false,
        shoujihaoma: false,
        shouhuodizhi: false,
        ispay: false,
        userid: false,
      },

      addressList: [
        "北京市朝阳区望京街道",
        "上海市浦东新区陆家嘴",
        "广州市天河区珠江新城",
        "深圳市南山区科技园",
        "杭州市余杭区未来科技城",
      ],
      _imgUrl: "",
    };
  },
  components: {
    wPicker,
  },
  computed: {
    zongjine: {
      get: function () {
        return 1 * this.ruleForm.jiage * this.ruleForm.spNumber;
      },
    },
    // spNumber: {
    //   get: function () {
    //     const regex = /^(?:[1-9]\d*(?:\.\d+)?|0\.\d*[1-9]\d*)$/;
    //     return regex.test(this.ruleForm.spNumber);
    //   },
    // },
  },
  async onLoad(options) {
    let table = uni.getStorageSync("nowTable");
    this._imgUrl = this.$base.url;
    // let res = await this.$api.session(table);
    // this.user = res.data;

    // ss读取
    this.ruleForm.yonghuming = this.user.yonghuming;
    this.ruleForm.yonghuxingming = this.user.yonghuxingming;
    this.ruleForm.shoujihaoma = this.user.shoujihaoma;

    // 如果有登陆，获取登陆后保存的userid
    this.ruleForm.userid = uni.getStorageSync("userInfo").userId;
    if (options.refid) {
      // 如果上一级页面传递了refid，获取改refid数据信息
      this.ruleForm.refid = options.refid;
      this.ruleForm.nickname = uni.getStorageSync("nickname");
    }
    // 如果是更新操作
    if (options.id) {
      this.ruleForm.id = options.id;
      // 获取信息
      res = await this.$api.info(`dingdanxinxi`, this.ruleForm.id);
      this.ruleForm = res.data;
    }
    // 跨表
    if (options.cross) {
      console.log("11111111", this.ruleForm);
      var obj = uni.getStorageSync("crossObj");
      for (var o in obj) {
        if (o == "dingdanbianhao") {
          this.ruleForm.dingdanbianhao = obj[o];
          this.ro.dingdanbianhao = true;
          continue;
        }
        if (o == "id") {
          this.ruleForm.shangpinId = obj[o];
          this.ro.shangpinId = true;
          continue;
        }
        if (o == "shangpinmingcheng") {
          this.ruleForm.shangpinmingcheng = obj[o];
          this.ro.shangpinmingcheng = true;
          continue;
        }
        if (o == "tupian") {
          this.ruleForm.tupian = obj[o];
          this.ro.tupian = true;
          continue;
        }
        if (o == "jiage") {
          this.ruleForm.jiage = obj[o];
          this.ro.jiage = true;
          continue;
        }
        if (o == "shuliang") {
          this.ruleForm.shuliang = obj[o];
          this.ro.shuliang = true;
          continue;
        }
        if (o == "zongjine") {
          this.ruleForm.zongjine = obj[o];
          this.ro.zongjine = true;
          continue;
        }
        if (o == "goumairiqi") {
          this.ruleForm.goumairiqi = obj[o];
          this.ro.goumairiqi = true;
          continue;
        }
        if (o == "nonghuzhanghao") {
          this.ruleForm.nonghuzhanghao = obj[o];
          this.ro.nonghuzhanghao = true;
          continue;
        }
        if (o == "nonghuxingming") {
          this.ruleForm.nonghuxingming = obj[o];
          this.ro.nonghuxingming = true;
          continue;
        }
        if (o == "yonghuming") {
          this.ruleForm.yonghuming = obj[o];
          this.ro.yonghuming = true;
          continue;
        }
        if (o == "yonghuxingming") {
          this.ruleForm.yonghuxingming = obj[o];
          this.ro.yonghuxingming = true;
          continue;
        }
        if (o == "shoujihaoma") {
          this.ruleForm.shoujihaoma = obj[o];
          this.ro.shoujihaoma = true;
          continue;
        }
        if (o == "shouhuodizhi") {
          this.ruleForm.shouhuodizhi = obj[o];
          this.ro.shouhuodizhi = true;
          continue;
        }
        if (o == "userid") {
          this.ruleForm.userid = obj[o];
          this.ro.userid = true;
          continue;
        }
		if (o == "remark") {
		  this.ruleForm.remark = obj[o];
		  this.ro.remark = true;
		  continue;
		}
      }
      Promise.all([this.getaddressList()]);
      this.ruleForm.shuliang = 0;
      this.ro.shuliang = false;
    }
    this.styleChange();
  },
  methods: {
    onInput(event) {
      let value = event.target.value;

      // 移除所有非数字字符
      value = value.replace(/[^\d]/g, "");

      // 移除前导零
      value = value.replace(/^0+/g, "");

      let number = 0;

      if (value !== "") {
        number = parseInt(value, 10);
        // 检查是否为有效正整数
        if (!isNaN(number) && number > 0) {
          // 更新为处理后的值（防止科学计数法等情况）
          value = number.toString();
        } else {
          // 无效输入时重置
          number = 0;
          value = "";
        }
      }
      // 更新表单数据
      this.ruleForm.spNumber = number;
      // 同步输入框显示值
      event.target.value = value;
    },
    async getaddressList() {
      try {
        let res = await this.$api.list("address", {
          userId: uni.getStorageSync("userInfo").userId,
        });
        if (res.code == 200) {
          this.addressList = res.rows.map((item) => item.detailAddress);
        }
      } catch (error) {}
    },

    addressChange(e) {
      this.ruleForm.shouhuodizhi = this.addressList[e.detail.value];
    },

    styleChange() {
      this.$nextTick(() => {
        // document.querySelectorAll('.app-update-pv .cu-form-group .uni-input-input').forEach(el=>{
        //   el.style.backgroundColor = this.addUpdateForm.input.content.backgroundColor
        // })
      });
    },
    // 多级联动参数
    goumairiqiChange(e) {
      this.ruleForm.goumairiqi = e.target.value;
      this.$forceUpdate();
    },

    tupianTap() {
      let _this = this;
      this.$api.upload(function (res) {
        _this.ruleForm.tupian = _this.$base.url + "upload/" + res.file;
        _this.$forceUpdate();
        _this.$nextTick(() => {
          _this.styleChange();
        });
      });
    },
    getUUID() {
      return new Date().getTime();
    },
    async onSubmitTap() {
      this.ruleForm.zongjine = this.zongjine;
      var obj = uni.getStorageSync("crossObj");
      var table = uni.getStorageSync("crossTable");
      obj.shuliang = obj.shuliang - this.ruleForm.spNumber;
      if (obj.shuliang < 0) {
        this.$utils.msg("数量数量不足");
        return;
      }
      // await this.$api.update(`${table}`, obj);
      if (
        this.ruleForm.zongjine &&
        !this.$validate.isIntNumer(this.ruleForm.zongjine)
      ) {
        this.$utils.msg(`总金额应输入整数`);
        return;
      }
      if (!this.ruleForm.userid) {
        this.$utils.msg(`用户id不能为空`);
        return;
      }
      // if (this.ruleForm.id) {
      // 	await this.$api.update(`dingdanxinxi`, this.ruleForm);
      // }
      else {
        console.log("this.ruleForm", this.ruleForm);

        const params = {
          userId: uni.getStorageSync("userInfo").userId,
          shangpinId: this.ruleForm.shangpinId,
          spNumber: 1,
          price: this.ruleForm.jiage,
          photo: this.ruleForm.tupian,
          name: this.ruleForm.shangpinmingcheng,
          remark: this.ruleForm.remark,
          spNumber: this.ruleForm.spNumber,
        };
        let res = await this.$api.add(`cart`, params);
        if (res.code == 200) {
        }
      }
      this.$utils.msgBack("提交成功");
    },

    optionsChange(e) {
      this.index = e.target.value;
    },
    bindDateChange(e) {
      this.date = e.target.value;
    },
    getDate(type) {
      const date = new Date();
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      if (type === "start") {
        year = year - 60;
      } else if (type === "end") {
        year = year + 2;
      }
      month = month > 9 ? month : "0" + month;
      day = day > 9 ? day : "0" + day;
      return `${year}-${month}-${day}`;
    },
    toggleTab(str) {
      this.$refs[str].show();
    },
  },
};
</script>

<style lang="scss">
.form-container {
  background: linear-gradient(135deg, #f8f9ff 0%, #f1f3fe 100%);
  min-height: 100vh;
  padding: 40rpx;
}

.form-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20rpx);
  border-radius: 24rpx;
  padding: 40rpx;
  box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.1);
}

.form-header {
  margin-bottom: 48rpx;

  .form-title {
    font-size: 44rpx;
    font-weight: 600;
    color: #2d3748;
    position: relative;
  }

  .decor-line {
    height: 4rpx;
    width: 80rpx;
    background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
    margin-top: 16rpx;
  }
}

.form-item {
  margin-bottom: 40rpx;
  padding: 24rpx 0;
  border-bottom: 1rpx solid #f1f3fe;

  .item-label {
    font-size: 30rpx;
    color: #4a5568;
    margin-bottom: 16rpx;
    display: flex;
    align-items: center;

    .cuIcon {
      margin-right: 12rpx;
      color: #667eea;
      font-size: 36rpx;
    }
  }

  .item-input {
	  height:100rpx;
    background: #f8f9ff;
    border-radius: 12rpx;
    padding: 20rpx;
    font-size: 28rpx;
    color: #2d3748;
  }
}

.upload-image {
  width: 200rpx;
  height: 200rpx;
  border-radius: 16rpx;
  border: 2rpx dashed #667eea;
}

.price-group {
  display: flex;
  justify-content: space-between;

  .half {
    width: 48%;
  }
}

.total-price {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .price-value {
    font-size: 36rpx;
    color: #ff4757;
    font-weight: 600;
  }
}

.date-picker,
.address-picker {
  padding: 20rpx;
  background: #f8f9ff;
  border-radius: 12rpx;
  color: #4a5568;
}

.submit-btn {
  background: linear-gradient(135deg, #667eea, #764ba2);
  border-radius: 60rpx;
  height: 96rpx;
  color: white;
  font-size: 34rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 40rpx;
  box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.3);
  transition: all 0.2s;

  &:active {
    transform: scale(0.98);
    opacity: 0.9;
  }

  .cuIcon-check {
    margin-left: 16rpx;
    font-size: 36rpx;
  }
}
</style>
